/**
 *  Copyright 2009-2014 by WWW.KNET.CN  All rights reserved.
 */
package com.domain.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.domain.model.Sysuser;
import com.domain.service.UserService;
import com.domain.util.ParseMD5;
import com.domain.util.commonUtil;

/**
 * TODO(这里用一句话描述这个类的作用)
 * 
 * @author liujie
 * @date 2015年4月15日 下午2:03:31
 * 
 */
@Controller
@RequestMapping("/login")
public class LoginController extends SuperController {
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
	@Resource
	private UserService userService;

	@RequestMapping("/login.html")
	public String toLogin() {
		return "frame/Login";
	}

	@RequestMapping(value = "/doLogin.html", method = { RequestMethod.GET, RequestMethod.POST, RequestMethod.HEAD })
	@ResponseBody
	public Map<String, Object> doLogin(HttpServletRequest request, Sysuser user) {
		logger.info(String.format("------------登录信息：用户名：{}，ID：{}", user.getUserName(), user.getId()));
		HttpSession session = request.getSession();
		Map<String, Object> map = new HashMap<String, Object>();
		String key = "";
		try {
			Sysuser sysuser = userService.getUserByUserName(user);
			if (sysuser != null && StringUtils.isNotEmpty(sysuser.getUserName())
					&& StringUtils.isNotEmpty(sysuser.getPassword())) {
				if (sysuser.getPassword().equals(ParseMD5.parseStrToMd5L32(user.getPassword()))) {
					session.setAttribute(commonUtil.CURRENTUSER, sysuser);
					key = "y";
				} else {
					key = "n";
				}
				
			} else {
				request.setAttribute("errMsg", "用户名或密码不正确！");
				key = "n";
			}
			key="y";

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("---------登录失败：" + e.getMessage());
			key = "n";
		}
		map.put("key", key);
	
		return map;
	}

	@RequestMapping(value = "/loginOut.html", method = { RequestMethod.GET, RequestMethod.POST, RequestMethod.HEAD })
	public String loginOut(HttpServletRequest request) {
		try {
			HttpSession session = request.getSession();
			Sysuser user = super.getCurrentUser(request);
			if (null != user) {
				session.removeAttribute(commonUtil.CURRENTUSER);
			}

			logger.info("------------------退出：" + new Date());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}

		return "frame/Login";
	}
}
